package com.woniu.houtai.controller;


import com.woniu.houtai.config.Converter;
import com.woniu.houtai.entity.Business;
import com.woniu.houtai.entity.Shop;
import com.woniu.houtai.service.BusinessService;
import com.woniu.houtai.utils.CookieUtils;
import com.woniu.houtai.utils.FileUtils;
import com.woniu.houtai.utils.JwtUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author firstGroup
 * @since 2023-02-22 09:45:58
 */
@Controller
@RequestMapping("/business")
public class BusinessController {

    private static final String pathName = "http://192.168.201.161:10002/imgs/";


    @Autowired
    BusinessService businessService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @RequestMapping("/register")
    @ResponseBody
    public String register(String username, String password, String repass, String emailCode, String email, MultipartFile imageUrl, String tel, HttpServletRequest request) {
        //验证邮箱验证码

        String emailCodeRedis = stringRedisTemplate.opsForValue().get(email);
        if (StringUtils.isEmpty(emailCodeRedis) || !emailCodeRedis.equals(emailCode)) {

            return "验证码错误";
        }
        // 验证用户名，邮箱，电话是否重复
        String result = businessService.confirmExist(username, password, email, tel);
        System.out.println(result);
        if (result == null) {
            //图片保存
            //图片保存路径
            String ip = "192.168.201.161";
            String filePath = "//" + ip + "/imgs/";
            //保存到文件中，返回文件名
            String newFileName = null;
            try {
                newFileName = FileUtils.copy(imageUrl, filePath);
            } catch (IOException e) {
                result = String.valueOf(e);
                throw new RuntimeException(e);
            }
            String sqlFileName = pathName + newFileName;
            if ((businessService.register(username, password, email, sqlFileName, tel) == 1)) {
                result = "ok";
            }
        }
        System.out.println(result);
        return result;

    }


    //登录功能
    @RequestMapping("login")
    @ResponseBody
    public String login(String name, String password, HttpServletResponse response) {
        Integer result = businessService.loginByName(name, password);
        // 0代表用户不存在，1代表密码错误，2.代表登录成功
        if (result == 0) {
            return "用户不存在";
        } else if (result == 1) {
            return "密码错误，请重试";
        } else {
            String token = JwtUtils.createToken(name, 15);
            CookieUtils.setUserToken2Cookie(response, token);
            //向redis中存储关联数据,作为 当token过期时是否还续期的标记
            stringRedisTemplate.opsForValue().set(token, name, 30, TimeUnit.MINUTES);

            return "ok";
        }
    }

    //修改密码
    @RequestMapping("updatePassword")
    @ResponseBody
    public String updatePassword(String oldPassword, String newPassword, String repass, HttpServletRequest request,HttpServletResponse response) {
        String userTokenFromCookie = CookieUtils.getUserTokenFromCookie(request);
        String account = JwtUtils.getAccountWithoutException(userTokenFromCookie);
        Business business = businessService.getBusinessByName(account);
        String pass = business.getPassword();
        if (!pass.equals(oldPassword)) {
            return ("密码错误");
        } else if (!repass.equals(newPassword)) {
            return ("两次密码输入不一致");
        } else if (newPassword.equals(pass)) {
            return ("新密码与原密码重复");
        } else {
            businessService.updatePassword(business.getId(), newPassword);
            CookieUtils.deleteUserTokenFromCookie(response);
            return ("ok");
        }

    }

    @RequestMapping("getBusiness")
    @ResponseBody
    public Business getBusiness(HttpServletRequest request){
        String userTokenFromCookie = CookieUtils.getUserTokenFromCookie(request);
        String account = JwtUtils.getAccountWithoutException(userTokenFromCookie);
        return businessService.getBusinessByName(account);
    }

    @RequestMapping("addCookie")
    @ResponseBody
    public String addCookie(String name, String value, HttpServletResponse response) {

        // 创建Cookie对象
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setMaxAge(30);
        cookie.setComment("测试cookie");
        response.addCookie(cookie);
        return "ok";
    }

    @RequestMapping("queryCookie")
    @ResponseBody
    public String queryCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && 1 < cookies.length; i++) {
            System.out.println(cookies[i]);
        }
        return "ok";
    }

    @RequestMapping("updateCookie")
    @ResponseBody
    public String updateCookie(String name, String value, HttpServletResponse response) {
        // 更新cookie 重写一遍

        // 创建Cookie对象
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setMaxAge(160);
        cookie.setComment("测试cookie");
        response.addCookie(cookie);
        return "ok";
    }

    @RequestMapping("delCookie")
    @ResponseBody
    public String delCookie(String name, String value, HttpServletResponse response) {
        //删除cookie cookie。setMaxAge(0)

        // 创建cookie对象
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        cookie.setComment("测试cookie");

        response.addCookie(cookie);

        return "ok";
    }

    @RequestMapping("currentUserName")
    @ResponseBody
    public Business currentUserName(HttpServletRequest request, Model model) {
        //从cookie中拿到UserToken
        String userTokenFromCookie = CookieUtils.getUserTokenFromCookie(request);
        //从userToken中解析出用户名
        String account = JwtUtils.getAccountWithoutException(userTokenFromCookie);
        Business businessByName = businessService.getBusinessByName(account);
        businessByName.setName(JwtUtils.getAccountWithoutException(userTokenFromCookie));
        return businessByName;
    }

    @RequestMapping("logout")
    @ResponseBody
    public String logout(HttpServletResponse response) {
        CookieUtils.deleteUserTokenFromCookie(response);
        System.out.println("运行logout");
        return "ok";
    }

    @RequestMapping("getEmailCode")
    @ResponseBody
    public String sendEmail(String email, HttpServletRequest request) {

        //正则表达式校验邮箱
        String regex = "^(.+)@(.+)$";
        Pattern pattern = Pattern.compile(regex);
        boolean isOK = pattern.matcher(email).matches();
        if (!isOK) {
            return "请输入正确邮箱";
        }
        rabbitTemplate.convertAndSend("sendEmailExchange", "sendEmail", email);
        return "ok";
    }

    @RequestMapping("confirmUsernameExist")
    @ResponseBody
    public String confirmUsernameExist(String username) {
        System.out.println(username);
        String result = null;
        result = businessService.confirmUsernameExist(username);
        System.out.println(result);
        return result;
    }


}

